package hongcaosp.app.android.video.online;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import hongcaosp.app.android.R;
import hongcaosp.app.android.common.BaseAdapter;
import hongcaosp.app.android.common.BaseHolder;
import hongcaosp.app.android.contact.EmptyLayoutHelper;
import hongcaosp.app.android.video.online.bean.OnlineMusic;
import hongcaosp.app.android.video.online.holder.OnlineMusicHolder;
import hongcaosp.app.android.video.online.iview.IOnlineCategoryView;
import hongcaosp.app.android.video.online.presenter.OnlineCategoryPresenter;
import xlj.lib.android.base.component.BaseActivity;
import xlj.lib.android.base.toastcompat.ToastManager;

public class OnLineCategoryActivity extends BaseActivity implements IOnlineCategoryView {

    private TextView tv_title;
    private MaterialRefreshLayout mrl_refresh;
    private RecyclerView rv_content;
    private EmptyLayoutHelper emptyLayoutHelper;

    private OnlineMusic onlineMusic;
    private BaseAdapter<OnlineMusic> adapter;

    private OnlineCategoryPresenter presenter;
    private DialogMusicDownload dialogMusicDownload;

    @Override
    protected void initData(Intent intent) {
        int id = getIntent().getIntExtra("id",-1);
        String content = getIntent().getStringExtra("content");
        String title = getIntent().getStringExtra("title");
        if (TextUtils.isEmpty(title)) {
            title = "搜索结果";
        }
        tv_title.setText(title);
        presenter = new OnlineCategoryPresenter(this,id,content);
        presenter.load();
    }

    @Override
    protected void initView() {
        findViewById(R.id.back_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        tv_title = findViewById(R.id.title);
        mrl_refresh = findViewById(R.id.mrl_refresh);
        rv_content = findViewById(R.id.rv_content);

        emptyLayoutHelper = new EmptyLayoutHelper(findViewById(R.id.empty_layout));
        emptyLayoutHelper.init("暂无该类型音乐","敬请期待我们添加更多音乐哟");
        mrl_refresh.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(MaterialRefreshLayout materialRefreshLayout) {
                adapter.setData(new ArrayList<OnlineMusic>());
                presenter.load();
            }

            @Override
            public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {
                presenter.loadMore();
            }
        });
        rv_content.setLayoutManager(new LinearLayoutManager(this,LinearLayout.VERTICAL,false));
        rv_content.setAdapter(adapter = new BaseAdapter<OnlineMusic>() {
            @NonNull
            @Override
            public BaseHolder<OnlineMusic> onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                return new OnlineMusicHolder(LayoutInflater.from(OnLineCategoryActivity.this).inflate(R.layout.item_online_music, parent, false), new OnlineMusicHolder.IOnItemClickListener() {
                    @Override
                    public void onItemClick(OnlineMusic music) {
                        if (onlineMusic != null) {
                            if (onlineMusic.getId().equals(music.getId())) {
                                changePlayStatus(onlineMusic.getStatus() != 0 ? 0 : 2);
                                rv_content.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        VoiceUtil.toggle();
                                    }
                                });
                                return;
                            }
                            playOver();
                        }
                        onlineMusic = music;
                        changePlayStatus(1);
                        rv_content.post(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    File rootFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/redgrass/txvodcache/music");
                                    if (!rootFile.exists()) {
                                        rootFile.mkdirs();
                                    }
                                    File musicFile = new File(rootFile,onlineMusic.getId() + ".mp3");
                                    if (musicFile.exists()) {
                                        VoiceUtil.play(OnLineCategoryActivity.this,musicFile,onPreparedListener,onCompletionListener,onErrorListener);
                                    } else {
                                        VoiceUtil.play(onlineMusic.getSongUrl(),onPreparedListener,onCompletionListener,onErrorListener);
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            ToastManager.getInstance().showToast("播放错误");
                                            playOver();
                                        }
                                    });
                                }
                            }
                        });
                    }

                    @Override
                    public void onUseClick(OnlineMusic music) {
                        if (dialogMusicDownload == null) {
                            dialogMusicDownload = new DialogMusicDownload(OnLineCategoryActivity.this, new DialogMusicDownload.IOnDownloadListener() {
                                @Override
                                public void onOver(String filePath) {
                                    Intent intent = new Intent();
                                    intent.putExtra("path", filePath);
                                    setResult(RESULT_OK, intent);
                                    finish();
                                }
                            });
                        }
                        dialogMusicDownload.download(music);
                    }
                });
            }
        });
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_online_category;
    }

    @Override
    public void data(List<OnlineMusic> musicList) {
        mrl_refresh.finishRefresh();
        mrl_refresh.setLoadMore(musicList.size() == 10);

        adapter.addData(musicList);
        adapter.notifyDataSetChanged();

        if (adapter.getData().isEmpty()) {
            emptyLayoutHelper.show();
        } else {
            emptyLayoutHelper.hide();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        VoiceUtil.release();
    }

    private MediaPlayer.OnPreparedListener onPreparedListener = new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            // 准备完成
            changePlayStatus(2);
        }
    };

    private MediaPlayer.OnCompletionListener onCompletionListener = new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            // 播放完成
            playOver();
        }
    };

    private MediaPlayer.OnErrorListener onErrorListener = new MediaPlayer.OnErrorListener() {
        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
            // 播放出错
            ToastManager.getInstance().showToast("播放错误");
            playOver();
            return false;
        }
    };

    private void changePlayStatus(int status) {
        if (onlineMusic != null) {
            onlineMusic.setStatus(status);
            adapter.notifyDataSetChanged();
        }
    }

    private void playOver() {
        if (onlineMusic != null) {
            onlineMusic.setStatus(0);
            adapter.notifyDataSetChanged();
        }
        rv_content.post(new Runnable() {
            @Override
            public void run() {
                VoiceUtil.release();
            }
        });
    }
}
